﻿using DBLibrary.DataBase;
using DBLibrary.Model.pojo;
using Martix.HikNetCamera;
using OpenCvSharp;
using PaddleOCRSharp;
using RantAIOCR.Common;
using RtspClientSharp;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using static Martix.HikNetCamera.CameraDevice;
using Rect = OpenCvSharp.Rect;

namespace RantLEDOCR.Common
{
    /// <summary>
    /// SC_ChinaAccentControl.xaml 的交互逻辑
    /// </summary>
    public partial class SC_ChinaAccentControl : UserControl
    {
        MainWindow mainWindow = (MainWindow)App.Current.MainWindow;
        Dictionary<string, Camera> Cameras = new Dictionary<string, Camera>();
        PortPara Sensor1, Sensor2;
        public event PropertyChangedEventHandler PropertyChanged;
        System.Threading.Timer mTimer;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null) PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        private PaddleOCREngine engine;
        OpenCvSharp.Dnn.Net net,net1;
        Yolov5Net.Scorer.YoloScorer<Yolov5Net.Scorer.Models.YoloCocoP5Model> scorer;
        Bitmap bitmap;
        Camera camera;
        Biz biz;
        float threhold= float.Parse(AppConfigurtaionServices.Configuration["Mask"]);
        private static  string isDebug = AppConfigurtaionServices.Configuration["debug"];
        private static string test = AppConfigurtaionServices.Configuration["Test"];
        private static string mode = AppConfigurtaionServices.Configuration["Mode"];
        static bool Debugging = !string.IsNullOrEmpty(isDebug) && isDebug == "1";
        BitmapImage displayImage;
        bool Logined = false;
        CameraDevice cameraDevice;
        static VideoStreamCallBack videoStreamCallBack;
        public SC_ChinaAccentControl()
        {
            InitializeComponent();
            biz = new Biz();
            AddStatiomTreeNode();

            OCRModelConfig config = null;
            OCRParameter oCRParameter = new OCRParameter();
            //oCRParameter.det_db_box_thresh = 0.8f;
            //oCRParameter.det_db_unclip_ratio = 0.9f;
            //初始化OCR引擎
            engine = new PaddleOCREngine(config, oCRParameter);
            string path = System.AppDomain.CurrentDomain.BaseDirectory;
            net = OpenCvSharp.Dnn.CvDnn.ReadNetFromOnnx(path + "Resources\\best.onnx");
            net1 = OpenCvSharp.Dnn.CvDnn.ReadNetFromOnnx(path + "Resources\\bestError.onnx");

            mTimer = new System.Threading.Timer(callback: new TimerCallback(TimerTaskAsync),
                state: null,
                dueTime: 2000,
                period: 2000);


        }
        private async void TimerTaskAsync(object timerState)
        {
            await Task.Run((async delegate
            {
                await CaptureVideo();
            }));
            //     mTimer.Change(-1, 5000);
        }
        private void TextBlock_MouseDown(object sender, MouseButtonEventArgs e)
        {
            this.OnCloseClick();
        }
        public async void AddStatiomTreeNode()
        {
            var categories = new List<Category>();
            {

            };
            var sensors = new Category
            {
                Name = "所有摄像头",
                SubCategories = new List<Category>
                {
                }
            };

            int i = 0;
            //取该分站传感器
            while (AppConfigurtaionServices.Configuration["Cameras:" + i.ToString() + ":Ip"] != null)
            {
                var s = AppConfigurtaionServices.Configuration["Cameras:" + i.ToString() + ":Ip"];
                var u = AppConfigurtaionServices.Configuration["Cameras:" + i.ToString() + ":UserName"];
                var p = AppConfigurtaionServices.Configuration["Cameras:" + i.ToString() + ":Password"];
                string[] ids= AppConfigurtaionServices.Configuration["Cameras:" + i.ToString() + ":Sensor1"].Split("-");
                Sensor1 = biz.GetPortParaByPortId(ids[0], ids[1],1);
                ids = AppConfigurtaionServices.Configuration["Cameras:" + i.ToString() + ":Sensor2"].Split("-");
                Sensor2 = biz.GetPortParaByPortId(ids[0], ids[1], 1);
                Cameras.Add(s, new Camera(s,u,p,Sensor1,Sensor2));
                sensors.SubCategories.Add(new Category() { Name = s });
                i++;
            }
            categories.Add(sensors);
            Sensors.ItemsSource = categories;
            camera=Cameras.FirstOrDefault().Value;

            CameraDevice.InitializeSdk();
            cameraDevice = new CameraDevice(camera.UserName, camera.PassWord, camera.Url, 8000);
            Logined =cameraDevice.Login();


        }

        //声明和注册路由事件
        public static readonly RoutedEvent CloseClickRoutedEvent =
            EventManager.RegisterRoutedEvent("CloseClick", RoutingStrategy.Bubble, typeof(EventHandler<RoutedEventArgs>), typeof(SC_ChinaAccentControl));
        //CLR事件包装
        public event RoutedEventHandler CloseClick
        {
            add { this.AddHandler(CloseClickRoutedEvent, value); }
            remove { this.RemoveHandler(CloseClickRoutedEvent, value); }
        }
        private void ProcessFRame(VideoStreamType type, byte[] data)
        {
            //lock (this)
            //{
            //    Mat frame;
            //    try
            //    {
            //        Debug.WriteLine("处理:");
            //        //if (type == VideoStreamType.Body)
            //        //    frame = Cv2.ImDecode(data, ImreadModes.Color);

            //    }
            //    catch (Exception ex)
            //    {
            //        Debug.WriteLine(ex.Message);
            //    }
            //}
        }
        //激发路由事件,借用Click事件的激发方法
        private async Task CaptureVideo()
        {
            try
            {
                isDebug = AppConfigurtaionServices.Configuration["debug"];
                Debugging = !string.IsNullOrEmpty(isDebug) && isDebug == "1";
                BitmapImage displayImage;
                ///异物遮挡检测
                //DirectoryInfo directory = new DirectoryInfo("d:/rant/2025-06-18/");

                //var files = directory.GetFiles();
                ////// 遍历当前目录下的所有文件
                //for(int i= 1;i<5;i++)
                //{
                //    App.Current.Dispatcher.Invoke(() =>
                //    {
                //        FileInfo imgfile = new("d:/rant/2025-06-18/"+i+".jpg");
                //        using var t = Cv2.ImRead(imgfile.FullName);
                //        // 处理当前文件
                //        Debug.WriteLine(imgfile.FullName);

                //        Recogniztion(t);


                //    });
                //    Task.Delay(3000).Wait();
                //}

                ////Cv2.ImShow("org", t);


                ////var v = GetDOI(t);


                ////      var v = GetMask(t);
                ////displayImage = MatToBitmapImage(frame);
                ////App.Current.Dispatcher.Invoke(() =>
                ////{
                ////    DisplayFrame.Source = displayImage;
                ////});
                ////var s = Recogniztion(frame);
                //////           label4.Text = string.Join(',', s);
                //return;


                if (Logined)
                {
                    try
                    {
                        byte[] data = cameraDevice.DirectlyCaptureJpegImage();
                        if (data.Length==0) { 
                            return;
                        }
                        using var frame = Cv2.ImDecode(data, ImreadModes.Color);
                        if (frame != null && !frame.Empty())
                        {
                            await Dispatcher.BeginInvoke(() =>
                            {
                                displayImage = ToImage(data);
                                DisplayFrame.Source = displayImage;
                            });
                            var s = Recogniztion(frame);
                            frame.Dispose();
                        }
                        else
                        {
                            LogUtil.Error("原始图像为空！");
                        }
    


                    }
                    catch (Exception ex)
                    {
                        await Task.Run(() => LogUtil.Error(ex.StackTrace));
                    }
                }
                else
                {
                    MessageBox.Show("请先连接摄像头！", "提示", MessageBoxButton.OK, MessageBoxImage.Stop);
                    return;
                }

            }
            catch (Exception ex)
            {
                LogUtil.Error("系统错误：" + ex.StackTrace);
            }
        }
    
        public BitmapImage ToImage(byte[] byteArray)
        {
            BitmapImage bmp = null;

            try
            {
                bmp = new BitmapImage();
                bmp.BeginInit();
                bmp.StreamSource = new MemoryStream(byteArray);
                bmp.EndInit();
            }
            catch(Exception ex)
            {
                Task.Run(() => LogUtil.Error(ex.StackTrace));
                bmp = null;
            }

            return bmp;
        }
        protected void OnCloseClick()
        {
            RoutedEventArgs args = new RoutedEventArgs(CloseClickRoutedEvent, this);
            this.RaiseEvent(args);
        }
        private Mat GetDOI(Mat input,int index,int delta)
        {
            Mat dst = new Mat();
            try
            {
                //图像大小。跟训练模型时用到的样本有关系
                Cv2.Resize(input, input, new OpenCvSharp.Size(640, 640));
                //    Cv2.ImShow("org", input);
                DateTime date1 = DateTime.Now;
                //将图片转化为tensor数据格式
                Mat tensor_mat = OpenCvSharp.Dnn.CvDnn.BlobFromImage(input, 1 / 255.0);
                //输入tensor数据，节点是images，这个是export.py定义好的
                net.SetInput(tensor_mat, "images");
                //输出数据，节点是output，这个也是export.py定义好的
                Mat result = net.Forward("output0");
                //维度变换
                result = result.Reshape(1, result.Size().Width);

                //预测框
                List<OpenCvSharp.Rect> boxes = new List<OpenCvSharp.Rect>();
                //根据阈值挑选出的识别出对象的框的序号
                List<int> indices = new List<int>();
                //预测框的得分
                List<float> scores = new List<float>();

                //循环结果数据，生成预测框大小得分等数据
                for (int r = 0; r < result.Rows; r++)
                {
                    float cx = result.At<float>(r, 0);
                    float cy = result.At<float>(r, 1);
                    float w = result.At<float>(r, 2);
                    float h = result.At<float>(r, 3);
                    float sc = result.At<float>(r, 4);
                    Mat confs = result.Row(r).ColRange(5, 6);
                    confs *= sc;
                    double minV, maxV;
                    Cv2.MinMaxIdx(confs, out minV, out maxV);
                    confs.Dispose();
                    scores.Add((float)maxV);
                    boxes.Add(new OpenCvSharp.Rect((int)(cx - w / 2), (int)(cy - h / 2), (int)w + 35, (int)h));
                    indices.Add(r);
                }

                int[] _indices;
                //使用opencv NMSBoxes函数处理数据，得到预测结果
                //其中0.6 0.45 是阈值
                OpenCvSharp.Dnn.CvDnn.NMSBoxes(boxes, scores, 0.2f, 0.45f, out _indices);
                var m = scores.Max();
                if (indices != null && indices.Count > 0)
                {
                    var maxScore = scores.Max();

                    //_indices 这个数组里保存了预测出的结果
                    for (int i = 0; i < _indices.Length; i++)
                    {
                        //预测框的序号
                        int idx = _indices[i];
                        if (scores[idx] == maxScore)
                        {


                            //裁剪DOI到新图像
                            try
                            {
                                Cv2.GetRectSubPix(input, new OpenCvSharp.Size(boxes[idx].Size.Width + 20, boxes[idx].Height + 25), new Point2f(boxes[idx].X + boxes[idx].Width / 2-delta, boxes[idx].Y + boxes[idx].Height / 2), dst, -1);
                                if (Debugging && dst != null && dst.Total() > 0)
                                    App.Current.Dispatcher.Invoke(() =>
                                    {
                                        Cv2.ImShow("DOI" + index, dst);
                                    });

                                break;
                            }
                            catch (Exception ex) { 
                                LogUtil.Error("GetDOI 错误："+ex.StackTrace);
                                break;
                            }
                        }
                    }
                    tensor_mat.Dispose();
                    result.Dispose();
                    return dst;
                }
                else
                {
                    tensor_mat.Dispose();
                    return input;
                }
            }
            catch (Exception ex)
            {
                Task.Run(()=>LogUtil.Error(ex.StackTrace));
                 return dst;
            }
        }
        private bool GetMask(Mat inputMat)
        {

            //将图片缩放到合适大小
            int threshold, width;
            Mat newFrame=new Mat();

                for (int i = 0; i < 2; i++)
                {
                    if (i == 0)
                    {
                        threshold = mainWindow.threshold1;
                        width = mainWindow.width1;
                    }
                    else
                    {
                        threshold = mainWindow.threshold2;
                        width = mainWindow.width2;
                    }


                    newFrame = inputMat.RowRange(250, 960 + 400).ColRange(width, width + 960);
                    //if (Debugging && newFrame!=null && newFrame.Total()>0)
                    //    App.Current.Dispatcher.Invoke(() =>
                    //    {
                    //        Cv2.ImShow("org" + i, newFrame);
                    //    });
                    //图像大小。跟训练模型时用到的样本有关系
                    Cv2.Resize(newFrame, newFrame, new OpenCvSharp.Size(640, 640));

                    //    Cv2.ImShow("org", input);
                    DateTime date1 = DateTime.Now;
                    //将图片转化为tensor数据格式
                    Mat tensor_mat = OpenCvSharp.Dnn.CvDnn.BlobFromImage(newFrame, 1 / 255.0);
                    //输入tensor数据，节点是images，这个是export.py定义好的
                    net1.SetInput(tensor_mat, "images");
                    //输出数据，节点是output，这个也是export.py定义好的
                    Mat result = net1.Forward("output0");
                    //维度变换
                    result = result.Reshape(1, result.Size().Width);

                    //预测框
                    List<OpenCvSharp.Rect> boxes = new List<OpenCvSharp.Rect>();
                    //根据阈值挑选出的识别出对象的框的序号
                    List<int> indices = new List<int>();
                    //预测框的得分
                    List<float> scores = new List<float>();

                    //循环结果数据，生成预测框大小得分等数据
                    for (int r = 0; r < result.Rows; r++)
                    {
                        float cx = result.At<float>(r, 0);
                        float cy = result.At<float>(r, 1);
                        float w = result.At<float>(r, 2);
                        float h = result.At<float>(r, 3);
                        float sc = result.At<float>(r, 4);
                        Mat confs = result.Row(r).ColRange(5, 6);
                        confs *= sc;
                        double minV, maxV;
                        Cv2.MinMaxIdx(confs, out minV, out maxV);
                        confs.Dispose();
                        scores.Add((float)maxV);
                        boxes.Add(new OpenCvSharp.Rect((int)(cx - w / 2), (int)(cy - h / 2), (int)w + 15, (int)h));
                        indices.Add(r);
                    }

                    int[] _indices;
                    //使用opencv NMSBoxes函数处理数据，得到预测结果
                    //其中0.6 0.45 是阈值
                    OpenCvSharp.Dnn.CvDnn.NMSBoxes(boxes, scores, threhold, 0.15f, out _indices);
                    var m = scores.Max();
                    if (_indices != null && _indices.Length > 0)
                    {
                        var maxScore = scores.Max();
                        Mat dst = new Mat();
                        try
                        {
                            //_indices 这个数组里保存了预测出的结果
                            for (int j = 0; j < _indices.Length; j++)
                            {
                                //预测框的序号
                                int idx = _indices[j];
                                // if (scores[idx] == maxScore)
                                {


                                    //裁剪DOI到新图像

                                    Cv2.GetRectSubPix(newFrame, new OpenCvSharp.Size(boxes[idx].Size.Width + 5, boxes[idx].Height + 25), new Point2f(boxes[idx].X + boxes[idx].Width / 2, boxes[idx].Y + boxes[idx].Height / 2), dst, -1);
                                    //if (Debugging && dst!=null && dst.Total()>0)
                                    //    App.Current.Dispatcher.Invoke(() =>
                                    //    {
                                    //        Cv2.ImShow("m" + i + " " + j, dst);
                                    //    });

                                    //break;
                                }
                                if (i == 0)
                                {
                                    App.Current.Dispatcher.Invoke(() =>
                                    {
                                        Mask1.Text = "遮挡";
                                        Mask1.Visibility = Visibility.Visible;
                                    });

                                }
                                else
                                    App.Current.Dispatcher.Invoke(() =>
                                    {
                                        Mask2.Text = "遮挡";
                                        Mask2.Visibility = Visibility.Visible;
                                    });
                            }

                        }
                        catch (Exception ex)
                        {
                            Task.Run(() => LogUtil.Error(ex.StackTrace));
                        }
                        finally {
                            dst.Dispose();
                        }
                    }
                    else
                    {
                        if (i == 0)
                        {
                            App.Current.Dispatcher.Invoke(() =>
                            {
                                Mask1.Text = "";
                                Mask1.Visibility = Visibility.Hidden;
                            });

                        }
                        else
                            App.Current.Dispatcher.Invoke(() =>
                            {
                                Mask2.Text = "";
                                Mask2.Visibility = Visibility.Hidden;
                            });
                    }
                    tensor_mat.Dispose();
                    result.Dispose();
                }
                newFrame.Dispose();

                return true;

        }
        public List<string> Recogniztion(Mat inputMat)
        {
            bool error;
            if (test=="1")
                error= GetMask(inputMat);

            int threshold, width,delta;
            OCRResult ocrResult;
            List<string> results = new List<string>();
            try
            {
                for (int i = 0; i < 2; i++)
                {
                    if (i == 0)
                    {
                        threshold = mainWindow.threshold1;
                        width = mainWindow.width1;
                        delta= mainWindow.delta1;
                    }
                    else
                    {
                        threshold = mainWindow.threshold2;
                        width = mainWindow.width2;
                        delta = mainWindow.delta2;
                    }


                    using var newFrame = inputMat.RowRange(450, 640 + 450).ColRange(width, width + 480);
                    if(newFrame.Empty())
                        continue;
                    if (Debugging)
                        App.Current.Dispatcher.Invoke(() =>
                        {
                            Cv2.ImShow("截图原始图像" + i, newFrame);
                        });


                    int low_H = 0, low_S = 0, low_V = 0;
                    int high_H = 180, high_S = 255, high_V = threshold;
                    var SrcMat = new Mat();
                    if (mode=="1")
                        SrcMat = GetDOI(newFrame, i,delta);
                    else
                        newFrame.CopyTo(SrcMat);
                    // Cv2.CvtColor(SrcMat, SrcMat, ColorConversionCodes.BGR2HSV);
                    //Cv2.ImWrite("d:\\ss.bmp", SrcMat);
                    //
                    using var DstMat = new Mat();

                    // Cv2.InRange(newFrame, new Scalar(low_H, low_S, low_V), new Scalar(high_H, high_S, high_V), DstMat);
                    if (SrcMat.Empty())
                        continue;
                    else
                        Cv2.InRange(SrcMat, new Scalar(low_H, low_S, low_V), new Scalar(high_H, high_S, high_V), DstMat);


                    using var kernel = Cv2.GetStructuringElement(0, new OpenCvSharp.Size(3, 3));

                    Cv2.BitwiseNot(DstMat, DstMat);

                    string result = "-1";
                    double weight = 0.6;
                    Cv2.MorphologyEx(DstMat, DstMat, MorphTypes.Open, kernel);
                    if (DstMat.Empty())
                        continue;
                    if (mode == "1")
                    {
                        using var background = new Mat(240, 320, MatType.CV_8UC1, Scalar.Black);
                        int x = (background.Width - DstMat.Width) / 2;
                        int y = (background.Height - DstMat.Height) / 2;
                        using var roi = background.SubMat(new Rect(x, y, DstMat.Width, DstMat.Height));

                        // 将小图片叠加到背景图的ROI区域
                        DstMat.CopyTo(roi);
                        if (Debugging && background != null && background.Total() > 0)
                        {
                            App.Current.Dispatcher.Invoke(() =>
                            {
                                Cv2.ImShow("二值化图像" + i, background);
                            });
                        }
                        ocrResult = engine.DetectText(background.ToBytes());
                    }
                    // 将小图片叠加到背景图的ROI区域
                    else
                        ocrResult = engine.DetectText(DstMat.ToBytes());
                    weight = ocrResult.TextBlocks.Max(s => s.Score);
                    bool recorded = false;
                    foreach (var t in ocrResult.TextBlocks)
                    {
                        if (t.Score >= weight)
                        {
                            Debug.WriteLine(t.Text);
                            recorded = true;
                            if (Regex.IsMatch(t.Text.Replace(" ", ""), @"^[+-]?\d*[.]?\d*$"))
                            {
                                float numFloat;
                                result = t.Text.Replace(" ", "");
                                if (i == 0 && camera.Sensor1 != null)
                                {

                                    App.Current.Dispatcher.Invoke(() =>
                                    {
                                        Label1.Content = camera.Sensor1.ToString2();

                                        try
                                        {
                                            if (!float.TryParse(result, out numFloat))
                                            {
                                                numFloat = 0F; // 或者其他默认值处理逻辑
                                            }
                                            SensorValue1.Text = result;
                                            HistoryData historyData = new HistoryData();
                                            historyData.CurValue = numFloat;
                                            historyData.SensorId = camera.Sensor1.SensorId;
                                            historyData.IsUpload2 = 0;
                                            historyData.IsUpload = 0;
                                            historyData.IsUpload3 = 0;
                                            historyData.IsUpload4 = 0;
                                            historyData.Status = 0;
                                            historyData.Time = DateTime.Now;
                                            historyData.Time2 = DateTime.Now;
                                            biz.AddAIHistoryData(historyData, DateTime.Now.ToString("yyMMdd"));
                                        }
                                        catch (Exception ex)
                                        {
                                            Task.Run(() => LogUtil.Error(ex.StackTrace));
                                        }
                                    });
                                }
                                else if (camera.Sensor2 != null)
                                {
                                    App.Current.Dispatcher.Invoke(() =>
                                    {
                                        Label2.Content = camera.Sensor2.ToString2();
                                        try
                                        {
                                            if (!float.TryParse(result, out numFloat))
                                            {
                                                numFloat = 0F; // 或者其他默认值处理逻辑
                                            }
                                            SensorValue2.Text = result;
                                            HistoryData historyData = new HistoryData();
                                            historyData.CurValue = numFloat;
                                            historyData.SensorId = camera.Sensor2.SensorId;
                                            historyData.IsUpload2 = 0;
                                            historyData.IsUpload = 0;
                                            historyData.IsUpload3 = 0;
                                            historyData.IsUpload4 = 0;
                                            historyData.Status = 0;
                                            historyData.Time = DateTime.Now;
                                            historyData.Time2 = DateTime.Now;
                                            biz.AddAIHistoryData(historyData, DateTime.Now.ToString("yyMMdd"));
                                        }
                                        catch (Exception ex)
                                        {
                                            Task.Run(() => LogUtil.Error(ex.StackTrace));
                                        }
                                    });
                                }
                                break;
                            }
                            else
                            {
                                if (i == 0 && camera.Sensor1 != null)
                                {

                                    App.Current.Dispatcher.Invoke(() =>
                                    {
                                        Label1.Content = camera.Sensor1.ToString2();
                                        SensorValue1.Text = t.Text;

                                    });
                                }
                                else if (camera.Sensor2 != null)
                                {
                                    App.Current.Dispatcher.Invoke(() =>
                                    {
                                        Label2.Content = camera.Sensor2.ToString2();
                                        SensorValue2.Text = t.Text;
                                    });
                                }
                                break;
                            }
                        }
                       
                    }
                    if(recorded==false)
                    {
                        if (i == 0 && camera.Sensor1 != null)
                        {

                            App.Current.Dispatcher.Invoke(() =>
                            {
                                Label1.Content = camera.Sensor1.ToString2();
                                SensorValue1.Text = "未识别";

                            });
                        }
                        else if (camera.Sensor2 != null)
                        {
                            App.Current.Dispatcher.Invoke(() =>
                            {
                                Label2.Content = camera.Sensor2.ToString2();
                                SensorValue2.Text = "未识别";
                            });
                        }
                        break;
                    }
                    kernel.Dispose();
                    DstMat.Dispose();
                    newFrame.Dispose();
                    SrcMat.Dispose();
                }
                return results;
            }
            catch (Exception ex)
            {
                Task.Run(()=>LogUtil.Error(ex.ToString()));
                return null;
            }

        }
        public Bitmap MatToBitmap(Mat image)
        {
            return OpenCvSharp.Extensions.BitmapConverter.ToBitmap(image);
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private void UserControl_Unloaded(object sender, RoutedEventArgs e)
        {
            CameraDevice.CleanUpSdk();
        }

        public BitmapImage MatToBitmapImage(Mat image)
        {
            Bitmap bitmap = MatToBitmap(image);
            using (MemoryStream stream = new MemoryStream())
            {
                bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png); // 坑点：格式选Bmp时，不带透明度

                stream.Position = 0;
                BitmapImage result = new BitmapImage();
                result.BeginInit();
                // According to MSDN, "The default OnDemand cache option retains access to the stream until the image is needed."
                // Force the bitmap to load right now so we can dispose the stream.
                result.CacheOption = BitmapCacheOption.OnLoad;
                result.StreamSource = stream;
                result.EndInit();
                result.Freeze();
                return result;
            }
        }

        private void Sensors_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            TreeView iten =sender as TreeView;
            if (iten != null) { 
                var cate=iten.SelectedItem as Category;
                if(cate.Name!="所有摄像头")
                    camera = Cameras.GetValueOrDefault(cate.Name);
                cameraDevice = new CameraDevice(camera.UserName, camera.PassWord, camera.Url, 8000);
                Logined = cameraDevice.Login();
            }
        }
    }
    class Camera
    {
        string userName;
        string passWord;

        public string Url { get; set; }
        public PortPara Sensor1 { get; set; }
        public PortPara Sensor2 { get; set; }

        public string UserName { get => userName; set => userName = value; }
        public string PassWord { get => passWord; set => passWord = value; }

        public Camera(string ip,string username,string password,PortPara p1,PortPara p2)
        {
            Url = ip;

            userName = username;
            passWord = password;
            Sensor1 = p1;
            Sensor2 = p2;

        }
    }
    public class Category
    {
        public string Name { get; set; }
        public List<Category> SubCategories { get; set; }
    }
}
